/**
 * 宽带预约列表
 */
(function($) {
  var pageCount = 1;
  var filterType = 3;
  var pageNumber = 0;
  var custPageNumber = 0;
  var groupList = new Array();
  var custList = new Array();
  var changeTariffSuccess = false;
  /*
  封装参数
  */
  var getMyParams = function() {
    var params = "?";
    var myParam = getParams();
    if (myParam) {
      params += myParam;

    }
    return params;
  };

  var isDigital = function(keyword) {
    var reg = /^[0-9]*$/;
    if (reg.test(keyword)) {
      return true;
    }
    return false;
  }

  var invalidParam = function(val, errorMsg) {
    console.log("val=" + val + ",msg=" + errorMsg);
    if (val) {
      return false;
    } else {
      showAlertMessage(errorMsg);
      return true;
    }
  }

  var sendSmsCode = function() {
    var phoneNumber = $("#phone").val();
    console.log("phoneNumber=" + phoneNumber);
    if (!phoneNumber || isNaN(phoneNumber) || phoneNumber.length != 11) {
      showAlertMessage("请填写正确的手机号码");
      return;
    }
    $('#modal').modal('open');
    sendSms(phoneNumber);
  }

  var smsVerifyCB = function() {
    console.log("短信验证码正确，跳转到资费详情页面");
  }

  var getVGroupUserDetailJsonParams = function(empCode, phone) {
    var params = {
      "BODY": {
        "WORN_SERV_CODE": "sVpmnMebBiCfm",
        "PHONE_NO": phone,
        "LOGIN_NO": empCode,
        "COMMON_INFO": {
          "PROVINCE_GROUP": "10008"
        }
      }
    };
    return params;
  };

  var getVGroupFeeListJsonParams = function(empCode, phone) {
    var params = {
      "BODY": {
        "WORN_SERV_CODE": "sVpmnBCodeCfm",
        "LOGIN_NO": empCode,
        "PHONE_NO": phone,
        "COMMON_INFO": {
          "PROVINCE_GROUP": "10008"
        }
      }
    };
    return params;
  };

  var getVGroupChangeTariffPackages = function(emCode, phone, prcID) {
    var params = {
      "BODY": {
        "WORN_SERV_CODE": "s3214Cfm",
        "PHONE_NO": phone,
        "GROUP_NO": "",
        "PRC_ID": prcID,
        "LOGIN_NO": emCode,
        "COMMON_INFO": {
          "PROVINCE_GROUP": "10008"
        }
      }
    };
    return params;
  }

  var showUserVGroupData = function(data) {
    root = data.ROOT;
    if (root.RETURN_CODE != 0) {
      showAlertMessage(root.RETURN_MSG);
      return;
    }
    var $detail = $('#amz-detail');
    var source = $detail.text();
    var template = Handlebars.compile(source);

    memInfo = root.OUT_DATA.MEB_INFO;
    var data = {
      info: memInfo,
      "error": "无公告信息!"
    };
    var html = template(data);
    $detail.before(html);
    $("#fee_name").attr("placeholder", "请选择V网资费");
  }

  var feeListClickFunc = function(object) {
    console.log("feeListClickFunc");
    var feeID = $(object).find("input[name='item_fee_id']").val();
    var feeName = $(object).find("div[name='item_fee_name']").html();
    $("#fee_id").val(feeID);
    $("#fee_name").val(feeName);
    $('#alert-fee-list').modal('close');
  }

  var itemOnClick = function(object, clickFunc) {
    $(object).off("click"); //取消li事件
    /*li事件*/
    $(object).on("click", function() {
      var $siblingsNode = $(this).siblings();
      var primaryClass = "select-item";
      var defaultColor = "#fff";
      var selectColor = "#0c79b1";

      if ($siblingsNode.hasClass(primaryClass)) {
        $siblingsNode.removeClass(primaryClass);
        $siblingsNode.css("background-color", defaultColor);
      }
      if ($(this).hasClass(primaryClass)) {
        $(this).removeClass(primaryClass);
        $(this).css("background-color", defaultColor);
      } else {
        $(this).addClass(primaryClass);
        $(this).css("background-color", selectColor);
      }
      clickFunc(this);
      event.stopPropagation();
    });
  }

  var showVGroupFeeListData = function(data) {
    root = data.ROOT;
    if (root.RETURN_CODE != 0) {
      showAlertMessage(root.RETURN_MSG);
      return;
    }
    var $fee_list = $('#amz-fee-list');
    var source = $fee_list.text();
    var template = Handlebars.compile(source);

    vfeeInfo = root.OUT_DATA.VGRP_INFO;
    for (i = 0; i < vfeeInfo.length; i++) {
      fee = vfeeInfo[i].FEE_NAME.split("->");
      if (fee.length == 2) {
        vfeeInfo[i].FEE_NUM = fee[0];
        vfeeInfo[i].FEE_NAME = fee[1];
      }
    }
    var data = {
      feelist: vfeeInfo,
      "error": "无费率数据!"
    };
    var html = template(data);
    $fee_list.before(html);
    itemOnClick("#fee-list > li", feeListClickFunc);
  }


  /*
  加载数据
  */
  var loadVGroupFeeList = function() {
    showLoadingBar($("#loadingFeeList"), true);
    var empCode = getParamValue("empCode");
    var phone = getParamValue("phone");
    var data = JSON.stringify(getVGroupFeeListJsonParams(empCode, phone));
    console.log("data=" + data);
    $.ajax({
      type: "post",
      contentType: "application/json",
      url: Constants.rpcCrmHost + "sUserOrdQry?token=" + getToken(),
      data: data,
      dataType: "json",
      headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
        showLoadingBar($("#loadingFeeList"), false);
        console.info(data);
        showVGroupFeeListData(data);
      },
      error: function(textStatus) {
        showLoadingBar($("#loadingFeeList"), false);
        showAlertMessage("获取资费列表失败！");
        console.info("request error:" + textStatus);
      }
    });
  };

  var changeTariffPackages = function() {
    phoneNumber = getParamValue("phone");
    if (invalidParam(phoneNumber, "参数异常：当前号码为空！")) {
      return;
    }
    feeID = $("#fee_id").val();
    if (invalidParam(feeID, "请选择V网资费")) {
      return;
    }
    var empCode = getParamValue("empCode");
    callChangeTariffPackages(phoneNumber, empCode, feeID);
  }

  var processSuccess = function() {
    params = getMyParams();
    if (params.indexOf("&phone=") != -1) {
      params = params.substring(0, params.indexOf("&phone="));
    }
    window.location.href = "vgroup_zfbg.html" + params;
  }  

  var callChangeTariffPackages = function(phone, empCode, feeId) {
    $('#modal-changeTarrifPackages').modal('open');
    var params = {
      'PHONE_NO': phone,
      'LOGIN_NO': empCode,
      "LOGIN_PHONE": getParamValue('phoneNumber'),
      'BUSINESS_CODE': feeId,
      'BUSINESS_NAME': $('#fee_name').val(),
      'USER_ID': getParamValue('userId'),
      'ORG_ID': getParamValue('storeId'),
      'SALE_TYPE': getParamValue('saleType')
    };
    $.ajax({
        type: "post",
        contentType: "application/json",
        data: JSON.stringify(params),
        url: Constants.apiV2Host + "h5/vgroup/submitZFBG",
        dataType: "json",
        async: true,
        headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
          $('#modal-changeTarrifPackages').modal('close');
          console.log('data=' + JSON.stringify(data));
          if (data.ROOT.RETURN_CODE == 0) {
            changeTariffSuccess = true;
            showAlertMessage("资费变更成功！");
          }else{
            showAlertMessage("资费变更失败！" + data.ROOT.RETURN_MSG);
          }
        },
        error: function(textStatus) {
          $('#modal-changeTarrifPackages').modal('close');
          showAlertMessage("资费变更失败！");
          console.info("request error:" + textStatus);
        }
    })
  }

  var invalidParam = function(val, errorMsg) {
    console.log("val=" + val + ",msg=" + errorMsg);
    if (val) {
      return false;
    } else {
      showAlertMessage(errorMsg);
      return true;
    }
  }

  var showAlertMessage = function(message) {
    $("#vgroup-alert-content").html(message);
    var options = {
      closeViaDimmer: false,
      dimmer: true
    };
    $("#vgroup-alert").modal(options);
  }

  var closeAlertMessage = function() {
    $("#vgroup-alert").modal('close');
  }

  /*
  加载数据
  */
  var loadUserVGroupDatas = function() {
    $('#modal').modal('open');
    var phone = getParamValue("phone");
    var empCode = getParamValue("empCode");
    var data = JSON.stringify(getVGroupUserDetailJsonParams(empCode, phone));
    console.log("data=" + data);
    $.ajax({
      type: "post",
      contentType: "application/json",
      url: Constants.rpcCrmHost + "sUserOrdQry?token=" + getToken(),
      data: data,
      dataType: "json",
      headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
        $('#modal').modal('close');
        console.info(data);
        showUserVGroupData(data);
      },
      error: function(textStatus) {
        $('#modal').modal('close');
        showAlertMessage("获取用户资费套餐失败！");
        console.info("request error:" + textStatus);
      }
    });
  };

  $(function() {
    $("#fee_name").on("click", function() {
      console.log("show feelist ");
      $('#alert-fee-list').modal('open');
    });
    $("#change_btn").on("click", function() {
      console.log("changeTariffPackages");
      changeTariffPackages();
    });
    $("#vgroup-alert-btn").on("click", function() {
      console.log("changeTariffPackages.finished");
      if(changeTariffSuccess==true){
        processSuccess();
      }
    });
    
    phone = getParamValue("phone");    
    $("#phone_number").html(phone);
    loadVGroupFeeList();
    loadUserVGroupDatas();
  });
})(jQuery);